package com.gla.market.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.gla.market.MainActivity;
import com.gla.market.R;
import com.gla.market.activity.HistoryOrderActivity;
import com.gla.market.activity.LoginActivity;
import com.gla.market.activity.PerSettingActivity;
import com.gla.market.activity.ReceivingAddressActivity;
import com.gla.market.activity.UpdateAddressActivity;
import com.gla.market.activity.UptoVipActivity;
import com.gla.market.constant.Constants;
import com.gla.market.utils.LoginCheckUtil;
import com.gla.market.utils.NetUtil;
import com.gla.market.utils.SharedPreferencesUtil;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

import org.apache.commons.lang3.StringUtils;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * 个人中心 界面
 */
public class AboutMe extends Fragment {
    public static final String UPDATE = "com.gla.market.UPDATE_ABOUT_ME";
    ImageButton receiving_address1,up_user1;
    Button logout;
    Button login;
    TextView personal_name;
    ImageView personal_photo;
    TextView moneyView;
    private TextView tv_is_vip;
    private ImageButton bt_all_order;
    Context mContext;
    RelativeLayout my_info;
    String photo_url;
    String name;
    int is_vip;
    Integer user_id;
    double money=0;
    private Receiver receiver;

    @Override
    public  void onDestroy() {
        super.onDestroy();
        mContext.unregisterReceiver(receiver);
    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup viewGroup,Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_personal);
        View view = inflater.inflate(R.layout.activity_personal,null);
        mContext = getContext();
        user_id = (Integer) SharedPreferencesUtil.get(mContext,"userInfo","user_id",1);
        initView(view);
        //根据登录状态改变控件
        changeView();
        //广播接收器
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(UPDATE);
        receiver = new Receiver();
        mContext.registerReceiver(receiver,intentFilter);
        is_vip = (int)SharedPreferencesUtil.get(mContext,"userInfo","is_vip",0);
        //个人信息修改按钮
        my_info.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(LoginCheckUtil.isLogin(mContext)) {
                    Intent intent = new Intent(mContext, PerSettingActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(mContext, "未登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
        //收获地址按钮
        receiving_address1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(LoginCheckUtil.isLogin(mContext)) {
                    Intent intent = new Intent(mContext, ReceivingAddressActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(mContext, "未登录", Toast.LENGTH_SHORT).show();
                }
               //finish();
            }
        });
        //退出登录按钮
        logout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(mContext, "已退出登录", Toast.LENGTH_SHORT).show();
                SharedPreferencesUtil.clear(mContext,"userInfo");
                changeView();
            }
        });
        //登录按钮
        login.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(mContext, LoginActivity.class);
                startActivityForResult(intent,0);
            }
        });
        bt_all_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (LoginCheckUtil.isLogin(mContext)) {
                    Intent intent = new Intent(mContext, HistoryOrderActivity.class);
                    intent.putExtra("id",4);
                    startActivity(intent);
                    //升级会员按钮
                }
            }
        });
        up_user1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (LoginCheckUtil.isLogin(mContext)) {
                    Intent intent = new Intent(mContext, UptoVipActivity.class);
                    startActivity(intent);
                } else {
                    Toast.makeText(mContext, "未登录", Toast.LENGTH_SHORT).show();
                }
            }
        });
        return view;
    }
    private void initView (View view){
        personal_name = view.findViewById(R.id.personal_name);
        System.out.println("username：" + personal_name);
        personal_photo = view.findViewById(R.id.personal_photo);
        my_info = view.findViewById(R.id.my_info);
        receiving_address1 = view.findViewById(R.id.receiving_address1);
        logout = view.findViewById(R.id.logout);
        tv_is_vip = view.findViewById(R.id.is_vip);
        up_user1 = view.findViewById(R.id.up_user1);
        login = view.findViewById(R.id.login);
        tv_is_vip.setText(is_vip == 0 ? "非会员用户" : "会员用户");
        moneyView = view.findViewById(R.id.personal_money);
        showMoney();

        bt_all_order = view.findViewById(R.id.history_order1);

    }

    @Override
    public void onResume() {
        super.onResume();
        getUserInfo();
    }

    private Handler uiHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case 1:
                    money = (double) msg.obj;
                    moneyView.setText("余额："+String.format("%.2f", money) + "元");
                    break;
            }
        }
    };

    class Receiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if(intent.getAction().equals(UPDATE)){
                changeView();
                getUserInfo();
            }
        }
    }
    /**
     * 根据登录状态改变控件
     */
    private void changeView () {
        getUserInfo();
        if (LoginCheckUtil.isLogin(mContext)) {
            logout.setVisibility(View.VISIBLE);
            login.setVisibility(View.GONE);
            personal_name.setText(name);
            System.out.println("名字：" + name);
            tv_is_vip.setVisibility(View.VISIBLE);
            if (!StringUtils.isBlank(photo_url)) {
                ImageLoaderConfiguration configuration = ImageLoaderConfiguration.createDefault(mContext);
                com.nostra13.universalimageloader.core.ImageLoader.getInstance().init(configuration);
                ImageLoader.getInstance().displayImage(photo_url, personal_photo);
            }
            tv_is_vip.setText(is_vip==0?"非会员用户":"会员用户");

        } else {
            login.setVisibility(View.VISIBLE);
            logout.setVisibility(View.GONE);
            tv_is_vip.setVisibility(View.GONE);
            personal_name.setText("未登录");
            personal_photo.setImageResource(R.drawable.hhn_user);
        }
    }

    @Override
    public void onActivityResult ( int requestCode, int resultCode, Intent data){
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == 0) {
            if (resultCode == 0) {
                changeView();
            }
        }
    }

    public void getUserInfo () {
        is_vip = (int) SharedPreferencesUtil.get(mContext, "userInfo", "is_vip", 0);
        photo_url = (String) SharedPreferencesUtil.get(mContext, "userInfo", "photo", "");
        name = (String) SharedPreferencesUtil.get(mContext, "userInfo", "name", "");
    }

    public void showMoney() {
        user_id = (Integer) SharedPreferencesUtil.get(mContext,"userInfo","user_id",1);
        String url = Constants.BASE_URL + Constants.GET_USER_MONEY+"/"+user_id;
        NetUtil.doGet(url, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                String result = response.body().string().trim();
                JSONObject object = JSON.parseObject(result);
                Message message = Message.obtain();
                System.out.println(object);
                if (!object.getString("message").contains("JWT") && object.getString("error")==null && object.getInteger("code")==100) {
                    message.what = 1;
                    message.obj = object.getDouble("data");
                } else {
                    message.what = 2;
                    message.obj = object.getString("message");
                }
                uiHandler.sendMessage(message);
            }
        });
    }
}